const express = require('express')
const router = express.Router()
const db = require('../db')
const multer = require('multer')
const path = require('path')
const fs = require('fs')

// 确保头像目录存在
const avatarsDir = path.join(process.cwd(), '..', 'public', 'avatars')
if (!fs.existsSync(avatarsDir)) {
  fs.mkdirSync(avatarsDir, { recursive: true })
}

// 配置 multer 存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, avatarsDir)
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, 'avatar-' + uniqueSuffix + path.extname(file.originalname))
  }
})

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 只接受图片文件
  if (file.mimetype.startsWith('image/')) {
    cb(null, true)
  } else {
    cb(new Error('只能上传图片文件！'), false)
  }
}

const upload = multer({ 
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制5MB
  }
})

// 获取用户信息
router.get('/:id', async (req, res) => {
  try {
    const [user] = await db.query('SELECT * FROM users WHERE id = ?', [req.params.id])
    res.json(user[0])
  } catch (error) {
    res.status(500).json({ error: '获取用户信息失败' })
  }
})

// 获取用户活动
router.get('/:id/activities', async (req, res) => {
  try {
    const [subscriptions] = await db.query('SELECT * FROM subscriptions WHERE user_id = ?', [req.params.id])
    const [likes] = await db.query('SELECT * FROM likes WHERE user_id = ?', [req.params.id])
    const [comments] = await db.query('SELECT * FROM comments WHERE user_id = ?', [req.params.id])
    const [shares] = await db.query('SELECT * FROM shares WHERE user_id = ?', [req.params.id])
    const [views] = await db.query('SELECT * FROM views WHERE user_id = ?', [req.params.id])
    
    res.json({
      subscriptions,
      likes,
      comments,
      shares,
      views
    })
  } catch (error) {
    res.status(500).json({ error: '获取用户活动失败' })
  }
})

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { account, password } = req.body
    const [users] = await db.query(
      'SELECT id, username, email, avatar, bio FROM users WHERE account = ? AND password = ?',
      [account, password]
    )
    
    if (users.length > 0) {
      res.json(users[0])
    } else {
      res.status(401).json({ error: '账号或密码错误' })
    }
  } catch (error) {
    res.status(500).json({ error: '登录失败' })
  }
})

// 用户注册
router.post('/register', async (req, res) => {
  try {
    const { username, email, account, password } = req.body
    const [result] = await db.query(
      'INSERT INTO users (username, email, account, password, avatar, bio) VALUES (?, ?, ?, ?, ?, ?)',
      [username, email, account, password, '/avatars/default.png', '']
    )
    res.json({ id: result.insertId })
  } catch (error) {
    res.status(500).json({ error: '注册失败' })
  }
})

// 添加订阅
router.post('/:subscriberId/subscribe/:subscribedId', async (req, res) => {
  try {
    const { subscriberId, subscribedId } = req.params
    if (!subscriberId || !subscribedId || subscriberId === 'undefined' || subscribedId === 'undefined') {
      return res.status(400).json({ error: '缺少必要参数' })
    }

    await db.query(
      'INSERT INTO subscriptions (subscriber_id, subscribed_id) VALUES (?, ?)',
      [subscriberId, subscribedId]
    )
    res.json({ message: '订阅成功' })
  } catch (error) {
    res.status(500).json({ error: '订阅失败' })
  }
})

// 取消订阅
router.delete('/:subscriberId/subscribe/:subscribedId', async (req, res) => {
  try {
    const { subscriberId, subscribedId } = req.params
    if (!subscriberId || !subscribedId || subscriberId === 'undefined' || subscribedId === 'undefined') {
      return res.status(400).json({ error: '缺少必要参数' })
    }

    await db.query(
      'DELETE FROM subscriptions WHERE subscriber_id = ? AND subscribed_id = ?',
      [subscriberId, subscribedId]
    )
    res.json({ message: '取消订阅成功' })
  } catch (error) {
    res.status(500).json({ error: '取消订阅失败' })
  }
})

// 检查是否已关注
router.get('/:subscriberId/isSubscribed/:subscribedId', async (req, res) => {
  try {
    const { subscriberId, subscribedId } = req.params
    if (!subscriberId || !subscribedId || subscriberId === 'undefined' || subscribedId === 'undefined') {
      return res.status(400).json({ error: '缺少必要参数' })
    }

    const [subscriptions] = await db.query(
      'SELECT * FROM subscriptions WHERE subscriber_id = ? AND subscribed_id = ?',
      [subscriberId, subscribedId]
    )

    res.json({ isSubscribed: subscriptions.length > 0 })
  } catch (error) {
    res.status(500).json({ error: '检查关注状态失败' })
  }
})

// 更新用户头像
router.post('/:id/avatar', upload.single('avatar'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '请选择要上传的图片' })
    }
    
    const userId = req.params.id
    const avatarPath = `/avatars/${req.file.filename}` // 相对路径
    
    // 删除旧头像（如果存在且不是默认头像）
    const [oldUser] = await db.query('SELECT avatar FROM users WHERE id = ?', [userId])
    const oldAvatarPath = oldUser[0]?.avatar
    if (oldAvatarPath && oldAvatarPath !== '/avatars/default.png') {
      const oldAvatarFullPath = path.join(__dirname, '..', 'public', oldAvatarPath)
      if (fs.existsSync(oldAvatarFullPath)) {
        fs.unlinkSync(oldAvatarFullPath)
      }
    }
    
    // 更新数据库中的头像路径
    await db.query(
      'UPDATE users SET avatar = ? WHERE id = ?',
      [avatarPath, userId]
    )

    res.json({ 
      message: '头像更新成功',
      avatar: avatarPath
    })
  } catch (error) {
    console.error('更新头像失败:', error)
    // 如果更新失败，删除上传的文件
    if (req.file) {
      const filePath = path.join(__dirname, '..', 'public', 'avatars', req.file.filename)
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath)
      }
    }
    res.status(500).json({ error: '更新头像失败' })
  }
})

// 获取用户喜欢的文章列表
router.get('/:id/likes', async (req, res) => {
  try {
    const [likes] = await db.query(
      `SELECT l.article_id
      FROM likes l
      WHERE l.user_id = ?
      ORDER BY l.create_time DESC`,
      [req.params.id]
    )
    // 只返回文章ID数组
    const articleIds = likes.map(like => like.article_id)
    res.json(articleIds)
  } catch (error) {
    console.error('获取喜欢列表失败:', error)
    res.status(500).json({ error: '获取喜欢列表失败' })
  }
})

// 获取用户的订阅列表
router.get('/:id/subscriptions', async (req, res) => {
  try {
    const [subscriptions] = await db.query(
      `SELECT s.subscribed_id
      FROM subscriptions s
      WHERE s.subscriber_id = ?
      ORDER BY s.create_time DESC`,
      [req.params.id]
    )
    // 只返回被订阅用户的ID数组
    const subscribedIds = subscriptions.map(sub => sub.subscribed_id)
    res.json(subscribedIds)
  } catch (error) {
    console.error('获取订阅列表失败:', error)
    res.status(500).json({ error: '获取订阅列表失败' })
  }
})

// 获取用户的评论列表
router.get('/:id/comments', async (req, res) => {
  try {
    const [comments] = await db.query(
      `SELECT DISTINCT article_id
      FROM (
        SELECT article_id, create_time
        FROM comments
        WHERE user_id = ?
        ORDER BY create_time DESC
      ) AS c`,
      [req.params.id]
    )
    // 只返回文章ID数组
    const articleIds = comments.map(comment => comment.article_id)
    res.json(articleIds)
  } catch (error) {
    console.error('获取评论列表失败:', error)
    res.status(500).json({ error: '获取评论列表失败' })
  }
})

// 获取用户的转发列表
router.get('/:id/shares', async (req, res) => {
  try {
    const [shares] = await db.query(
      `SELECT s.article_id
      FROM shares s
      WHERE s.user_id = ?
      ORDER BY s.create_time DESC`,
      [req.params.id]
    )
    // 只返回文章ID数组
    const articleIds = shares.map(share => share.article_id)
    res.json(articleIds)
  } catch (error) {
    console.error('获取转发列表失败:', error)
    res.status(500).json({ error: '获取转发列表失败' })
  }
})

// 获取用户的粉丝列表
router.get('/:id/followers', async (req, res) => {
  try {
    const [followers] = await db.query(
      `SELECT u.id, u.username, u.avatar, u.bio
      FROM users u
      INNER JOIN subscriptions s ON u.id = s.subscriber_id
      WHERE s.subscribed_id = ?
      ORDER BY s.create_time DESC`,
      [req.params.id]
    )
    res.json(followers)
  } catch (error) {
    console.error('获取粉丝列表失败:', error)
    res.status(500).json({ error: '获取粉丝列表失败' })
  }
})

module.exports = router 